
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepSeekOCR-ESG报告准确率测试平台</title>
    
    <!-- Bootstrap 5.3 CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <!-- Chart.js -->
    <script src="https://cdn.bootcdn.net/ajax/libs/Chart.js/4.4.0/chart.min.js"></script>
    
    <style>
        body {
            background-color: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem 0;
            margin-bottom: 2rem;
        }
        .card {
            border: none;
            box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
            transition: all 0.3s ease;
        }
        .card:hover {
            box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15);
        }
        .upload-zone {
            border: 2px dashed #dee2e6;
            border-radius: 0.5rem;
            padding: 2rem;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .upload-zone:hover {
            border-color: #667eea;
            background-color: #f8f9ff;
        }
        .upload-zone.dragover {
            border-color: #667eea;
            background-color: #f8f9ff;
        }
        .progress-bar {
            transition: width 0.3s ease;
        }
        .result-card {
            background: white;
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin-bottom: 1rem;
        }
        .accuracy-badge {
            font-size: 1.2rem;
            padding: 0.5rem 1rem;
        }
        .text-comparison {
            font-family: 'Courier New', monospace;
            font-size: 0.9rem;
            line-height: 1.5;
        }
        .highlight-error {
            background-color: #ffe6e6;
            text-decoration: line-through;
        }
        .highlight-missing {
            background-color: #fff3cd;
            text-decoration: underline wavy #ff6b6b;
        }
    </style>
</head>
<body>
    <!-- 头部 -->
    <div class="header">
        <div class="container">
            <h1 class="mb-0">
                <i class="fas fa-eye"></i>
                DeepSeekOCR-ESG报告准确率测试平台
            </h1>
            <p class="mb-0 opacity-75">专业评估OCR在ESG报告场景下的识别准确率</p>
        </div>
    </div>

    <div class="container">
        <!-- 步骤导航 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-md-3">
                                <div class="step-item">
                                    <div class="step-number bg-primary text-white rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">1</div>
                                    <h6 class="mt-2 mb-0">上传ESG报告</h6>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="step-item">
                                    <div class="step-number bg-secondary text-white rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">2</div>
                                    <h6 class="mt-2 mb-0">执行OCR识别</h6>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="step-item">
                                    <div class="step-number bg-secondary text-white rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">3</div>
                                    <h6 class="mt-2 mb-0">上传标准答案</h6>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="step-item">
                                    <div class="step-number bg-secondary text-white rounded-circle d-inline-flex align-items-center justify-content-center" style="width: 40px; height: 40px;">4</div>
                                    <h6 class="mt-2 mb-0">生成测试报告</h6>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 上传区域 -->
        <div class="row">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-upload"></i>
                            上传ESG报告
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="upload-zone" id="reportUploadZone">
                            <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                            <h6>拖拽文件到此处或点击上传</h6>
                            <p class="text-muted small">支持PDF、PNG、JPG格式</p>
                            <input type="file" id="reportFileInput" accept=".pdf,.png,.jpg,.jpeg" style="display: none;">
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="display: none;" id="uploadProgress">
                                <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-check-circle"></i>
                            上传标准答案
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="upload-zone" id="groundTruthUploadZone">
                            <i class="fas fa-file-text fa-3x text-muted mb-3"></i>
                            <h6>上传人工标注文件</h6>
                            <p class="text-muted small">TXT格式，使用---PAGE_BREAK---分隔页面</p>
                            <input type="file" id="groundTruthFileInput" accept=".txt" style="display: none;">
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body text-center">
                        <button class="btn btn-primary btn-lg me-3" id="performOCRBtn" disabled>
                            <i class="fas fa-eye"></i>
                            执行OCR识别
                        </button>
                        <button class="btn btn-success btn-lg me-3" id="calculateAccuracyBtn" disabled>
                            <i class="fas fa-calculator"></i>
                            计算准确率
                        </button>
                        <button class="btn btn-info btn-lg" id="downloadReportBtn" style="display: none;">
                            <i class="fas fa-download"></i>
                            下载测试报告
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 结果显示区域 -->
        <div class="row mt-4" id="resultsArea" style="display: none;">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-chart-bar"></i>
                            测试结果
                        </h5>
                    </div>
                    <div class="card-body">
                        <!-- 总体准确率 -->
                        <div class="row mb-4">
                            <div class="col-md-4">
                                <div class="text-center">
                                    <h3 class="text-primary">
                                        <span id="charAccuracy">--</span>%
                                    </h3>
                                    <p class="text-muted mb-0">字符级准确率</p>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="text-center">
                                    <h3 class="text-success">
                                        <span id="paraAccuracy">--</span>%
                                    </h3>
                                    <p class="text-muted mb-0">段落级准确率</p>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="text-center">
                                    <h3 class="text-info">
                                        <span id="fieldRecall">--</span>%
                                    </h3>
                                    <p class="text-muted mb-0">关键字段召回率</p>
                                </div>
                            </div>
                        </div>

                        <!-- 图表 -->
                        <div class="row">
                            <div class="col-md-6">
                                <canvas id="accuracyChart" height="200"></canvas>
                            </div>
                            <div class="col-md-6">
                                <canvas id="timeChart" height="200"></canvas>
                            </div>
                        </div>

                        <!-- 详细结果表格 -->
                        <div class="mt-4">
                            <h6>详细结果</h6>
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>页面</th>
                                            <th>字符级准确率</th>
                                            <th>段落级准确率</th>
                                            <th>关键字段召回率</th>
                                            <th>处理时间</th>
                                        </tr>
                                    </thead>
                                    <tbody id="resultsTableBody">
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 文本对比区域 -->
        <div class="row mt-4" id="comparisonArea" style="display: none;">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-eye"></i>
                            文本对比
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6>OCR识别结果</h6>
                                <pre id="ocrText" class="text-comparison bg-light p-3 rounded"></pre>
                            </div>
                            <div class="col-md-6">
                                <h6>标准答案</h6>
                                <pre id="groundTruthText" class="text-comparison bg-light p-3 rounded"></pre>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.3.0/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // 全局变量
        let currentReportId = null;
        let ocrResults = null;
        let accuracyResults = null;

        // API基础URL
        const API_BASE = 'http://localhost:8000/api';

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeEventListeners();
        });

        function initializeEventListeners() {
            // 文件上传区域
            const reportUploadZone = document.getElementById('reportUploadZone');
            const groundTruthUploadZone = document.getElementById('groundTruthUploadZone');
            
            // 文件输入
            const reportFileInput = document.getElementById('reportFileInput');
            const groundTruthFileInput = document.getElementById('groundTruthFileInput');

            // 拖拽上传
            setupDragDrop(reportUploadZone, reportFileInput);
            setupDragDrop(groundTruthUploadZone, groundTruthFileInput);

            // 点击上传
            reportUploadZone.addEventListener('click', () => reportFileInput.click());
            groundTruthUploadZone.addEventListener('click', () => groundTruthFileInput.click());

            // 文件选择
            reportFileInput.addEventListener('change', handleReportUpload);
            groundTruthFileInput.addEventListener('change', handleGroundTruthUpload);

            // 按钮事件
            document.getElementById('performOCRBtn').addEventListener('click', performOCR);
            document.getElementById('calculateAccuracyBtn').addEventListener('click', calculateAccuracy);
            document.getElementById('downloadReportBtn').addEventListener('click', downloadReport);
        }

        function setupDragDrop(zone, input) {
            zone.addEventListener('dragover', (e) => {
                e.preventDefault();
                zone.classList.add('dragover');
            });

            zone.addEventListener('dragleave', () => {
                zone.classList.remove('dragover');
            });

            zone.addEventListener('drop', (e) => {
                e.preventDefault();
                zone.classList.remove('dragover');
                
                const files = e.dataTransfer.files;
                if (files.length > 0) {
                    input.files = files;
                    input.dispatchEvent(new Event('change'));
                }
            });
        }

        async function handleReportUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('file', file);

            try {
                showProgress(true);
                
                const response = await fetch(`${API_BASE}/upload-report`, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                
                if (response.ok) {
                    currentReportId = data.report_id;
                    updateStepIndicator(1, true);
                    document.getElementById('performOCRBtn').disabled = false;
                    
                    showToast('报告上传成功', 'success');
                } else {
                    throw new Error(data.detail || '上传失败');
                }
            } catch (error) {
                showToast(error.message, 'error');
            } finally {
                showProgress(false);
            }
        }

        async function handleGroundTruthUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            const formData = new FormData();
            formData.append('report_id', currentReportId);
            formData.append('ground_truth', file);

            try {
                const response = await fetch(`${API_BASE}/upload-ground-truth`, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                
                if (response.ok) {
                    updateStepIndicator(3, true);
                    document.getElementById('calculateAccuracyBtn').disabled = false;
                    showToast('标准答案上传成功', 'success');
                } else {
                    throw new Error(data.detail || '上传失败');
                }
            } catch (error) {
                showToast(error.message, 'error');
            }
        }

        async function performOCR() {
            if (!currentReportId) {
                showToast('请先上传报告', 'warning');
                return;
            }

            try {
                showProgress(true);
                
                const formData = new FormData();
                formData.append('report_id', currentReportId);

                const response = await fetch(`${API_BASE}/perform-ocr`, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                
                if (response.ok) {
                    ocrResults = data;
                    updateStepIndicator(2, true);
                    showToast('OCR识别完成', 'success');
                } else {
                    throw new Error(data.detail || '识别失败');
                }
            } catch (error) {
                showToast(error.message, 'error');
            } finally {
                showProgress(false);
            }
        }

        async function calculateAccuracy() {
            if (!currentReportId) {
                showToast('请先完成前面的步骤', 'warning');
                return;
            }

            try {
                showProgress(true);
                
                const formData = new FormData();
                formData.append('report_id', currentReportId);

                const response = await fetch(`${API_BASE}/calculate-accuracy`, {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                
                if (response.ok) {
                    accuracyResults = data;
                    updateStepIndicator(4, true);
                    displayResults(data);
                    document.getElementById('downloadReportBtn').style.display = 'inline-block';
                    showToast('准确率计算完成', 'success');
                } else {
                    throw new Error(data.detail || '计算失败');
                }
            } catch (error) {
                showToast(error.message, 'error');
            } finally {
                showProgress(false);
            }
        }

        function displayResults(data) {
            document.getElementById('resultsArea').style.display = 'block';
            document.getElementById('comparisonArea').style.display = 'block';

            // 更新总体准确率
            document.getElementById('charAccuracy').textContent = 
                (data.overall_accuracy.character_accuracy * 100).toFixed(1);
            document.getElementById('paraAccuracy').textContent = 
                (data.overall_accuracy.paragraph_accuracy * 100).toFixed(1);
            document.getElementById('fieldRecall').textContent = 
                (data.overall_accuracy.field_recall * 100).toFixed(1);

            // 更新表格
            const tbody = document.getElementById('resultsTableBody');
            tbody.innerHTML = '';
            
            Object.entries(data.page_results).forEach(([page, result]) => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${page}</td>
                    <td>${(result.character_accuracy * 100).toFixed(1)}%</td>
                    <td>${(result.paragraph_accuracy * 100).toFixed(1)}%</td>
                    <td>${(result.field_recall * 100).toFixed(1)}%</td>
                    <td>${result.processing_time?.toFixed(2) || '--'}s</td>
                `;
            });

            // 绘制图表
            drawCharts(data);
        }

        function drawCharts(data) {
            // 准确率图表
            const ctx1 = document.getElementById('accuracyChart').getContext('2d');
            new Chart(ctx1, {
                type: 'bar',
                data: {
                    labels: Object.keys(data.page_results),
                    datasets: [{
                        label: '字符级准确率',
                        data: Object.values(data.page_results).map(r => r.character_accuracy * 100),
                        backgroundColor: 'rgba(102, 126, 234, 0.8)',
                        borderColor: 'rgba(102, 126, 234, 1)',
                        borderWidth: 1
                    }, {
                        label: '段落级准确率',
                        data: Object.values(data.page_results).map(r => r.paragraph_accuracy * 100),
                        backgroundColor: 'rgba(75, 192, 192, 0.8)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100
                        }
                    }
                }
            });

            // 处理时间图表
            const ctx2 = document.getElementById('timeChart').getContext('2d');
            new Chart(ctx2, {
                type: 'line',
                data: {
                    labels: Object.keys(data.page_results),
                    datasets: [{
                        label: '处理时间 (秒)',
                        data: Object.values(data.page_results).map(r => r.processing_time || 0),
                        backgroundColor: 'rgba(255, 159, 64, 0.2)',
                        borderColor: 'rgba(255, 159, 64, 1)',
                        borderWidth: 2,
                        tension: 0.1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }

        async function downloadReport() {
            if (!currentReportId) return;

            try {
                const response = await fetch(`${API_BASE}/download-report/${currentReportId}`);
                
                if (response.ok) {
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = `esg_ocr_test_report_${currentReportId}.json`;
                    a.click();
                    window.URL.revokeObjectURL(url);
                } else {
                    throw new Error('下载失败');
                }
            } catch (error) {
                showToast(error.message, 'error');
            }
        }

        function updateStepIndicator(step, completed) {
            const stepNumber = document.querySelectorAll('.step-number')[step - 1];
            if (completed) {
                stepNumber.classList.remove('bg-secondary');
                stepNumber.classList.add('bg-success');
            } else {
                stepNumber.classList.remove('bg-success');
                stepNumber.classList.add('bg-secondary');
            }
        }

        function showProgress(show) {
            const progress = document.getElementById('uploadProgress');
            progress.style.display = show ? 'block' : 'none';
        }

        function showToast(message, type) {
            const toast = document.createElement('div');
            toast.className = `alert alert-${type === 'success' ? 'success' : type === 'error' ? 'danger' : 'warning'} alert-dismissible fade show position-fixed`;
            toast.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
            toast.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.remove();
            }, 3000);
        }
    </script>
</body>
</html>
